﻿using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using QTMusic.BaseClasses;

namespace QTMusic.UserControls
{
    public partial class UserRegistration : System.Web.UI.UserControl
    {
        override protected void OnInit(EventArgs e)
        {
            string onBlurScript = Page.ClientScript.GetPostBackEventReference(InputUsername, "OnBlur");
            InputUsername.Attributes.Add("onblur", onBlurScript);

            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                string ctrlName = Request.Params[Page.postEventSourceID];
                string args = Request.Params[Page.postEventArgumentID];

                HandleCustomPostbackEvent(ctrlName, args);
            }
        }

        private void HandleCustomPostbackEvent(string ctrlName, string args)
        {
            if (ctrlName == InputUsername.UniqueID && args == "OnBlur")
            {
                ValidateUsername.Validate();
                if (ValidateUsername.IsValid)
                {
                    ServerResponse.Text = "Success";
                }
            }
        }

        protected void RegistUserHandler(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                ServerResponse.Text = "Success";
                //now add user to database
                SqlConnection conn = new SqlConnection(Common.connString);
                SqlCommand sql = new SqlCommand("INSERT INTO [user] (user_name, user_password, user_email, user_dateofbirth, user_friend_count, user_signup_date, user_acc_type, user_visited_count, user_pic) VALUES(@usname, @pass, @email, @dob, @friendcount, @signupdate, @acctype, @visited, @pic)", conn);

                sql.Parameters.AddWithValue("@usname", InputUsername.Text);
                sql.Parameters.AddWithValue("@pass", InputPassword.Text);
                sql.Parameters.AddWithValue("@email", InputEmail.Text);
                sql.Parameters.AddWithValue("@dob", InputDob.Text);
                sql.Parameters.AddWithValue("@friendcount", 0);
                sql.Parameters.AddWithValue("@signupdate", DateTime.Now.ToShortDateString());
                sql.Parameters.AddWithValue("@acctype", "normal");
                sql.Parameters.AddWithValue("@visited", 0);
                sql.Parameters.AddWithValue("@pic", Common.defaultImage);
                //sql.Parameters.AddWithValue("@pic", null);

                conn.Open();
                int result = sql.ExecuteNonQuery();
                conn.Close();

                if (result != 0)
                {
                    ServerResponse.Text = "inserted";

                    //get newly inserted userid
                    
                    sql = new SqlCommand("SELECT max(user_id) AS last_id FROM [user]", conn);

                    conn.Open();
                    SqlDataReader reader = sql.ExecuteReader();
                    reader.Read();
                    int newlyInsertedUserId = (int)reader["last_id"];
                    conn.Close();

                    HttpCookie cookie;
                    if ((cookie = Request.Cookies["QTCookie"]) == null)
                        cookie = new HttpCookie("QTCookie");
                    cookie["Name"] = InputUsername.Text;
                    cookie["ID"] = newlyInsertedUserId.ToString();
                    cookie.Expires = DateTime.Now.AddYears(1);

                    Response.Cookies.Add(cookie);
                    Response.Redirect("~/Websites/Profile.aspx?id=" + newlyInsertedUserId);
                }
                else
                {
                    ServerResponse.Text = "failed";
                }
            }
        }
        
        protected void vld_username(Object source, ServerValidateEventArgs e)
        {
            //Assume username is valid
            e.IsValid = true;
            //check if username = null
            if (e.Value == "")
            {
                e.IsValid = false;
                ValidateUsername.ErrorMessage = "Missing!";
            }
            else
            {
                SqlConnection conn = new SqlConnection(Common.connString);
                SqlCommand sql = new SqlCommand("SELECT * FROM [user] WHERE user_name=@usname", conn);

                sql.Parameters.AddWithValue("@usname", e.Value);

                DataSet ds = new DataSet();
                SqlDataAdapter sda = new SqlDataAdapter(sql);
                sda.Fill(ds, "User");

                if (ds.Tables["User"].Rows.Count != 0)
                {
                    e.IsValid = false;
                    ValidateUsername.ErrorMessage = "Duplicated!";
                }
                conn.Close();
            }
            return;
        }
    }
}